import React, { createContext, useState } from 'react';
import classNames from 'classnames';
import { MenuItemProps } from './menuItem';


type MenuMode = 'horizontal' | 'vertical';

type MenuSelectCallback = (selectedIndex: number) => void;

export interface MenuProps {
    /** 菜单的默认索引值 */
    defaultIndex?: number;
    /** 菜单的模式 */
    mode?: MenuMode;
    className?: string;
    /** 菜单的点击回调函数 */
    onSelect?: MenuSelectCallback;
    style?: React.CSSProperties;
    children?: React.ReactNode;

}

interface IMenuContext {
    index: number;
    onSelect?: MenuSelectCallback;
    mode?: MenuMode;
}

export const MenuContext = createContext<IMenuContext>({ index: 0 });

const Menu = (props: MenuProps) => {

    const { defaultIndex = 0, mode = "horizontal", className, onSelect, style, children } = props;
    const [currentActive, setCurrentActive] = useState(defaultIndex);
    const classes = classNames('menu', className, {
        'menu-vertical': mode === 'vertical',
        'menu-horizontal': mode === 'horizontal'
    })

    const handleClick = (index: number) => {
        setCurrentActive(index);
        if (onSelect) {
            onSelect(index);
        }
    }

    const passedContext: IMenuContext = {
        index: currentActive ? currentActive : 0,
        onSelect: handleClick,
        mode: mode,
    }

    const renderChildren = () => {
        return React.Children.map(children, (child, index) => {
            const childElement = child as React.FunctionComponentElement<MenuItemProps>;

            const { displayName } = childElement.type
            // console.log("displayName", displayName)
            if (displayName === 'MenuItem' || displayName === 'SubMenu') {
                return React.cloneElement(childElement, {
                    index: index,
                })
            } else {
                console.error("Warning: Menu has a child which is not a MenuItem component")
            }
        })
    }

    return (
        <ul className={classes} style={style} data-testid="test-menu">
            <MenuContext.Provider value={passedContext}>
                {renderChildren()}
            </MenuContext.Provider>
        </ul>
    )

}




export default Menu;